package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * 与 FindDuplicate287一样
 * @Author fengye
 * @Date 2023/4/8 11:34
 **/
public class HasCycleList141 {

    public boolean hasCycle1(ListNode head) {
        if(head==null) {
            return false;
        }
        ListNode pos = head.next;
        Set<ListNode> set = new HashSet<>();
        while(pos != null) {
            if(set.contains(pos)) {
                return true;
            }
            set.add(pos);
            pos = pos.next;
        }

        return false;
    }

    public boolean hasCycle(ListNode head) {
        if (head == null) {
            return false;
        }
        // 快慢指针
        ListNode fast = head.next;
        ListNode slow = head;

        while (slow != fast) {
            if(fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }

        return true;
    }
}
